package com.mz.mattress.admin.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mz.mattress.api.entity.MemberMer;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface MemberMerMapper extends BaseMapper<MemberMer> {

    Page<MemberMer> listPage(Page page,
                             @Param("mobile") String mobile,
                             @Param("status") Integer status,
                             @Param("type") Integer type,
                             @Param("startTime") String startTime,
                             @Param("endTime") String endTime);

    @Select("select * from mz_member_mer where mobile=#{mobile} and deleted=0 limit 1")
    MemberMer selectByMobile(@Param("mobile") String mobile);

    @Select("select * from mz_member_mer where open_id=#{openId} and deleted=0")
    List<MemberMer> selectByOpenId(@Param("openId") String openId);

    @Delete("delete from mz_member_mer where id=#{memberId}")
    void deleteByMemberId(@Param("memberId") Long memberId);

    @Select("select balance from mz_member_mer where id=#{memberId} for update")
    Integer lockMember(@Param("memberId") Long memberId);

    //提现使用
//    @Update("update mz_member_mer set balance=balance-#{change},sum_cash_out=sum_cash_out+#{change} where id=#{memberId}")
//    void subtractBalance(@Param("memberId") Long memberId, @Param("change") Integer change);

    //冻结金额  扣除可用金额 加上冻结金额  乐观锁
    @Update("update mz_member_mer set balance=balance-#{change},freeze=freeze+#{change},version=version+1 where id=#{memberId} and version=#{version}")
    Integer freezeMoney(@Param("memberId") Long memberId, @Param("change") Integer change, @Param("version") Integer version);

    //冻结金额 生效 乐观锁
    @Update("update mz_member_mer set freeze=freeze-#{change},sum_cash_out=sum_cash_out+#{change},version=version+1 where id=#{memberId} and version=#{version}")
    Integer freezeEffect(@Param("memberId") Long memberId, @Param("change") Integer change, @Param("version") Integer version);

    //冻结金额 释放 乐观锁
    @Update("update mz_member_mer set balance=balance+#{change},freeze=freeze-#{change},version=version+1 where id=#{memberId} and version=#{version}")
    Integer freezeRelease(@Param("memberId") Long memberId, @Param("change") Integer change, @Param("version") Integer version);

    @Update("update mz_member_mer set type=null,type_id=null where id=#{memberId}")
    Integer resetType(@Param("memberId") Long memberId);

}
